package pers.wk.queues.simple;

import com.rabbitmq.client.*;
import pers.wk.config.MQConfig;
import pers.wk.utils.MQConnectionUtils;

import java.text.MessageFormat;

/**
 * 简单队列-消费者
 * 同一个会话， consumerTag 是固定的 可以做此会话的名字，
 * deliveryTag 每次接收消息+1，可以做此消息处理通道的名字。
 * 消费者重新建立连接，consumerTag会变，deliveryTag会重新从1开始递增
 */
public class Customer {

    public static void main(String[] args) {

        ConnectionFactory connectionFactory = MQConnectionUtils.getConnectionFactory("/");
        Connection connection = null;
        Channel channel = null;
        try {
            //2.创建连接
            connection = connectionFactory.newConnection();
            //3.通过连接获取通道Channel
            channel = connection.createChannel();

            channel.queueDeclare(MQConfig.QueueNames.SIMPLE_QUEUE_NAME,
                    false, false, false, null);
            System.out.println("简单队列-消费者启动。。。");

            //自动应答
            channel.basicConsume(MQConfig.QueueNames.SIMPLE_QUEUE_NAME, true, (consumerTag, message) -> {
                System.out.println("consumerTag = " + consumerTag);
                //@FunctionalInterface DeliverCallback
                System.out.println(MessageFormat.format("简单队列-消费者获取消息：【{1}】{0}",
                        new String(message.getBody(), "UTF-8")
                        , message.getEnvelope().getDeliveryTag()));
            }, (consumerTag) -> {
                //@FunctionalInterface CancelCallback
            });

            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6: 关闭通道
            MQConnectionUtils.close(connection, channel);
        }
    }
}
